<template>
  <div class="commonBoxmp">
    <TableV2
      :apiFunction="listJob"
      class="flex1"
      ref="tableV2Ref"
      :columns="state.columnData"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <h3 class="mx15">任务管理</h3>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      <template #operation>
        <el-table-column label="操作" fixed="right" width="160px" align="left">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)"
              >修改</el-link
            >
            <el-link type="primary" @click="handleDelete(scope.row)"
              >删除</el-link
            >
            <el-dropdown @command="handleMoreTool($event, scope.row)">
              <el-link class="ml10" type="primary">
                更多
                <el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-link>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleRun"
                    >执行一次</el-dropdown-item
                  >
                  <el-dropdown-item command="handleView"
                    >任务详细</el-dropdown-item
                  >
                  <el-dropdown-item command="handleJobLog"
                    >调度日志</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </template>
    </TableV2>

    <el-dialog
      v-model="state.userVisible"
      :title="state.title"
      width="50%"
      destroy-on-close
      center
    >
      <el-form
        ref="ruleFormRef"
        :model="state.form"
        :rules="state.rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input
                v-model="state.form.jobName"
                placeholder="请输入任务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <selectDict
                class="w100"
                dictCode="sys_job_group"
                v-model="state.form.jobGroup"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <selectDict
                class="w100"
                dictCode="sys_job_status"
                v-model="state.form.status"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="invokeTarget">
              <template #label>
                <div class="aic">
                  <el-tooltip placement="top">
                    <template #content>
                      Bean调用示例：ryTask.ryParams('ry')
                      <br />Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                      <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                    </template>
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                  调用方法
                </div>
              </template>
              <el-input
                v-model="state.form.invokeTarget"
                placeholder="请输入调用目标字符串"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input
                v-model="state.form.cronExpression"
                placeholder="请输入内容"
              >
                <template #append>
                  <el-link @click="handleShowCron"> 生成表达式</el-link>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="state.form.misfirePolicy">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="state.form.concurrent">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="state.form.status">
                <el-radio
                  v-for="dict in dict.sys_job_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.userVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="state.openCron"
      title="Cron表达式生成器"
      width="50%"
      destroy-on-close
      center
    >
      <crontab
        @hide="state.openCron = false"
        @fill="crontabFill"
        :expression="state.expression"
      ></crontab>
    </el-dialog>

    <el-dialog
      v-model="state.openView"
      title="任务详细"
      width="50%"
      destroy-on-close
      center
    >
      <el-form ref="ruleFormRef" label-width="120px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：">{{
              state.form.jobId
            }}</el-form-item>
            <el-form-item label="任务名称：">{{
              state.form.jobName
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{
              jobGroupFormat(state.form)
            }}</el-form-item>
            <el-form-item label="创建时间：">{{
              state.form.createTime
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{
              state.form.cronExpression
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{
              parseTime(state.form.nextValidTime)
            }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标方法：">{{
              state.form.invokeTarget
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">
              <div v-if="state.form.status == 0">正常</div>
              <div v-else-if="state.form.status == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="state.form.concurrent == 0">允许</div>
              <div v-else-if="state.form.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="state.form.misfirePolicy == 0">默认策略</div>
              <div v-else-if="state.form.misfirePolicy == 1">立即执行</div>
              <div v-else-if="state.form.misfirePolicy == 2">执行一次</div>
              <div v-else-if="state.form.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.openView = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";
import Crontab from "/@/components/Crontab/index.vue";
import DictTag from "/@/components/DictTag/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import {
  listJob,
  getJob,
  delJob,
  addJob,
  updateJob,
  runJob,
  changeJobStatus,
} from "/@ts/axios/urlApi/monitor/job";
import formatTool from "/@ts/hooks/format";
import { routerPush } from "/@ts/hooks/route";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, getDict, selectDictLabel } = formatTool();

const state: any = reactive({
  // 表格基础配置 start
  form: {},
  title: "",
  rules: {
    jobName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
    invokeTarget: [
      { required: true, message: "调用目标字符串不能为空", trigger: "blur" },
    ],
    cronExpression: [
      { required: true, message: "cron执行表达式不能为空", trigger: "blur" },
    ],
  },
  dateRange: [], //时间范围筛选

  height: 0,
  tableData: [],
  columnData: [
    {
      label: "任务编号",
      prop: "jobId",
      visible: true,
    },
    {
      label: "任务名称",
      prop: "jobName",
      visible: true,
    },
    {
      label: "任务组名",
      prop: "jobGroup",
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.jobGroup}
            dataType="primary"
            options={dict.sys_job_group}
          ></DictTag>
        );
      },
    },

    {
      label: "调用目标字符串",
      prop: "invokeTarget",
      visible: true,
    },
    {
      label: "cron执行表达式",
      prop: "cronExpression",
      visible: true,
    },
    {
      label: "状态",
      prop: "status",
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
          ></DictTag>
        );
      },
    },
  ],
  loading: false,
  // 表格基础配置 end
  openCron: false,
  openView: false,
  expression: "",
});
// 表格基础配置 start
const pageInfo = reactive({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryParams: any = reactive({
  pageNum: 1,
  pageSize: 10,
  deptId: undefined,
});
const handleView = (row: any) => {
  getJob(row.jobId).then((response: any) => {
    state.form = response.data;
    state.openView = true;
  });
};
const handleRun = (row: any) => {
  const jobIds = row.jobId;
  ElMessageBox.confirm('确认要立即执行一次"' + row.jobName + '"任务吗？')
    .then(function () {
      return runJob(jobIds, row.jobGroup);
    })
    .then(() => {
      ElMessage.success("执行成功");
      getList();
    })
    .catch(function () {});
};
const handleJobLog = (row: any) => {
  const jobId = row.jobId || 0;
  routerPush("/monitor/job-log/index/" + jobId);
};
//更多操作
const handleMoreTool = (val: string, row: any) => {
  switch (val) {
    case "handleRun":
      handleRun(row);
      break;

    case "handleView":
      handleView(row);
      break;
    case "handleJobLog":
      handleJobLog(row);
      break;
  }
};
const getCurrentColumns = (data: Column[]) => {
  state.columnData = data;
};
const getHeight = (height: number) => {
  state.height = height;
};
const handleSizeChange = (size: number) => {
  pageInfo.pageSize = size;
  getList();
};
const handleCurrentChange = (page: number) => {
  pageInfo.currentPage = page;
  getList();
};
const crontabFill = (value: any) => {
  console.log("value :>> ", value);
  state.form.cronExpression = value;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};
const handleShowCron = () => {
  state.expression = state.form.cronExpression;
  state.openCron = true;
};
// 任务组名字典翻译
const jobGroupFormat = (row: any, column?: any) => {
  return selectDictLabel(dict.sys_job_group, row.jobGroup);
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.jobId != undefined) {
    updateJob(state.form).then((response: any) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addJob(state.form).then((response: any) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const jobIds = row.jobId;
  ElMessageBox.confirm('是否确认删除定时任务编号为"' + jobIds + '"的数据项？')
    .then(function () {
      return delJob(jobIds);
    })
    .then(() => {
      ElMessage.success("删除成功");
      getList();
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  const jobId = row.jobId;
  getJob(jobId).then((response: any) => {
    state.title = "修改任务";
    state.form = response.data;
    state.userVisible = true;
  });
};
const handleAdd = () => {
  state.form = {};
  state.title = "添加任务";
  state.userVisible = true;
};
// 表格基础配置 end
//查询用户列表
const getList = () => {
  state.loading = true;
  queryParams.pageNum = pageInfo.currentPage;
  queryParams.pageSize = pageInfo.pageSize;
  listJob(addDateRange(queryParams, state.dateRange)).then((response: any) => {
    state.tableData = response.rows;
    pageInfo.total = response.total;
    state.loading = false;
  });
};
const handleDetail = (jobId: any) => {
  routerPush({
    path: "/system/dict-data/index/" + jobId,
  });
};
let dict: any = reactive({
  sys_job_status: [],
  sys_job_group: [],
});
const ruleFormRef = ref<FormInstance>();
onMounted(async () => {
  dict.sys_job_status = await getDict("sys_job_status");
  dict.sys_job_group = await getDict("sys_job_group");
  getList();
});
</script>

<style scoped lang="scss"></style>
